package com.madou.dbtool.redis.panel.ui;

import com.madou.bean.BeanFactory;
import com.madou.common.annotation.HideClass;
import com.madou.dbtool.common.dto.Complex;
import com.madou.dbtool.common.icon.AllIcons;
import com.madou.dbtool.common.messages.DBToolBundle;
import com.madou.dbtool.language.enums.ContentTypeEnum;
import com.madou.dbtool.redis.manager.RedisSourceManager;
import com.madou.dbtool.redis.panel.converter.ListToCommandCellDataConverter;
import com.madou.dbtool.redis.panel.dataloader.RedisScanTableDataLoader;
import com.madou.dbtool.redis.panel.dataloader.RedisSlowLogTableDataLoader;
import com.madou.dbtool.redis.panel.ui.types.TypePanelFactory;
import com.madou.dbtool.ui.table.MColumn;
import com.madou.dbtool.ui.table.MRow;
import com.madou.dbtool.ui.table.MTable;
import com.madou.dbtool.ui.table.enums.DataType;
import com.madou.dbtool.ui.terminal.util.StringUtils;
import com.madou.inters.util.MessageUtil;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

@HideClass
public class RedisDataPanel extends JPanel {
    private JPanel panel;
    private JTextField searchText;
    private MTable leftTable;
    private JLabel info;
    private JPanel viewPanel;
    private JButton refresh;
    private JButton remove;
    private JButton refreshScan;
    private JScrollPane leftScrollPanel;
    private JTextField commandField;
    private JButton runButton;
    private static List<MColumn> columns = new ArrayList<>();
    private RedisSlowLogTableDataLoader dataLoader;
    String defaultKey = null;
    String selectKey = null;
    RedisSourceManager redisSourceManager;
    int dbIndex = 0;
    static {
        MColumn first = new MColumn();
        first.setName("first");
        first.setTitle("ID");
        first.setWidth(30);
        first.setCanEdit(false);
        columns.add(first);

        MColumn second = new MColumn();
        second.setName("second");
        second.setTitle("KEY");
        second.setCanEdit(false);
        second.setWidth(300);
        columns.add(second);
    }

    public RedisDataPanel(RedisSourceManager redisSourceManager,String key,int dbIndex){
        this.redisSourceManager = redisSourceManager;
        this.defaultKey = key;
        this.selectKey = key;
        this.dbIndex = dbIndex;
    }

    /**
     * 初始化布局
     */
    public void init(){
        this.setLayout(new BorderLayout());
        this.add(panel,BorderLayout.CENTER);
        this.initLeftEvent();
        this.initButton();
        loadLeftData();
        if(!StringUtils.isEmpty(selectKey)){
            loadRightData();
        }
        Color color = UIManager.getColor("EditorPane.background");
        if(color==null){
            color = Color.WHITE;
        }
        leftScrollPanel.getViewport().setBackground(color);
        leftScrollPanel.setBackground(color);
        leftTable.setBackground(color);
        viewPanel.setBackground(color);
    }

    private void initButton() {
        commandField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                if(e.getKeyCode()==KeyEvent.VK_ENTER){
                    doExecCommand();
                }
            }
        });
        runButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                doExecCommand();
            }
        });
    }

    private void doExecCommand(){
        String command = commandField.getText();
        if(!StringUtils.isEmpty(command)){
            try {
                redisSourceManager.execute(dbIndex, command);
                BeanFactory.getInstance().getBean(MessageUtil.class).showInfoMessage(DBToolBundle.message("redis.view.data.panel.tip.run.success"),"Tip");
            }catch (Exception exception){
                BeanFactory.getInstance().getBean(MessageUtil.class).showErrorDialog(exception.getMessage(),"Tip");
            }
        }
    }

    /**
     * 加载左表格数据
     */
    private void loadLeftData() {
        leftTable.addSearchKeyword("keyword",searchText.getText());
        leftTable.setPageSize(200);
        try {
            leftTable.load();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载左表格数据
     */
    private void loadRightData() {
        viewPanel.removeAll();
        if(!StringUtils.isEmpty(selectKey)) {
            byte[] type = (byte[]) redisSourceManager.execute(dbIndex,"TYPE " + selectKey);
            Object ttl = redisSourceManager.execute(dbIndex,"PTTL " + selectKey);
            String keyType = new String(type);
            String temp = String.format("Key: %s , Type: %s , TTL: %d ms",selectKey, keyType, ttl);
            info.setText(temp);
            JComponent typePanel = null;
            try {
                typePanel = TypePanelFactory.createTypePanel(keyType, selectKey, redisSourceManager,dbIndex);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (typePanel != null) {
                viewPanel.add(typePanel, BorderLayout.CENTER);
            }
        }
    }

    /**
     * 初始化左边的事件
     */
    private void initLeftEvent() {
        searchText.setText(defaultKey==null?"":defaultKey);
        searchText.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent keyEvent) {
                loadLeftData();
            }
        });
        leftTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent mouseEvent) {
                int selectedRow = leftTable.getSelectedRow();
                if(selectedRow>-1) {
                    Complex<MRow, MColumn> temp = (Complex<MRow, MColumn>) leftTable.getComplexValueAt(selectedRow, 1);
                    selectKey = (String) temp.getFirst().getColumn(temp.getSecond().getName());
                    loadRightData();
                }
            }
        });
    }

    private void createUIComponents() {
        leftTable = new MTable(columns,new RedisScanTableDataLoader(redisSourceManager,dbIndex));
        refresh = new JButton();
        refresh.setIcon(AllIcons.Common.REFRESH);
        refresh.setCursor(new Cursor(Cursor.HAND_CURSOR));
        refresh.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                loadRightData();
            }
        });

        refreshScan = new JButton();
        refreshScan.setIcon(AllIcons.Common.REFRESH);
        refreshScan.setCursor(new Cursor(Cursor.HAND_CURSOR));
        refreshScan.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                loadLeftData();
            }
        });

        remove = new JButton();
        remove.setIcon(AllIcons.Common.REMOVE);
        remove.setCursor(new Cursor(Cursor.HAND_CURSOR));
        remove.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                removeSelectKey();
            }
        });
    }

    /**
     * 删除key
     */
    public void removeSelectKey(){
        if(!StringUtils.isEmpty(selectKey)){
            Object execute = redisSourceManager.execute(dbIndex,"del " + selectKey);
            selectKey=null;
            loadLeftData();
            loadRightData();
        }
    }

    /**
     * 销毁
     */
    public void desroty() {
        redisSourceManager.close();
    }
}
